import React, { useState, useEffect } from 'react';
import styles from './index.less';
import dayjs from 'dayjs';
import calendar from './changeDate.js';

const weekList = ['日', '一', '二', '三', '四', '五', '六'];
const todayDate = new Date(); // 今日日期，实际项目中推荐从接口拿服务器日期用
const todayZeroDate = new Date(
  todayDate.getFullYear(),
  todayDate.getMonth(),
  todayDate.getDate(),
); // 今日零点的日期，用于后续转换时间戳后日期大小的比较

const Page = ({ getYearAndMouth, changeMonthNum, changeYearNum }) => {
  const [cYear, setCYear] = useState(changeYearNum);
  const [cMonth, setCMonth] = useState(changeMonthNum);
  const [dateList, setDateList] = useState([]);
  const [choseDateList, setChoseDateList] = useState([
    dayjs().format('YYYY-MM-DD'),
  ]);

  useEffect(() => {
    onChangeYear2(changeYearNum);
    onChangeMonth2(changeMonthNum);
  }, [changeMonthNum, changeYearNum]);

  const onChangeYear = (num: number) => {
    setCYear(cYear + num);
  };

  const onChangeMonth = (num: number) => {
    if (cMonth + num <= 0) {
      setCYear(cYear - 1);
      setCMonth(12 - (cMonth + num));
    } else if (cMonth + num >= 13) {
      setCYear(cYear + 1);
      setCMonth(cMonth + num - 12);
    } else {
      setCMonth(cMonth + num);
    }
  };
  const onChangeYear2 = (num: number) => {
    setCYear(num);
  };

  const onChangeMonth2 = (num: number) => {
    setCMonth(num);
  };

  // 获取指定年月的当月所有天的数组
  const getDateListByMonth = (year, month) => {
    const days = new Date(year, month, 0).getDate();
    return new Array(days).fill(null).map((v, i) => i + 1);
  };

  // 获取指定年月的1号是周几
  const getWeekOfFirstDay = (year, month) => {
    return new Date(year, month - 1, 1).getDay();
  };

  // 获取日期渲染数据
  useEffect(() => {
    // 上月的部分数据
    const week = getWeekOfFirstDay(cYear, cMonth);
    const lastMonthNums = getDateListByMonth(cYear, cMonth - 1);
    const preffixList = lastMonthNums
      .slice(week === 0 ? -7 : -week)
      .map((v) => ({
        id: dayjs(`${cYear}-${cMonth - 2}-${v}`).format('YYYY-MM-DD'),
        // id: tools.formatDate(new Date(cYear, cMonth - 2, v), '{y}-{m}-{d}'),
        monthType: 'last',
        disabled: true,
        num: v,
      }));
    // 当月的数据
    const curMonthNums = getDateListByMonth(cYear, cMonth);
    const currentList = curMonthNums.map((v) => {
      const vDate = new Date(cYear, cMonth - 1, v);
      const isRedDot = +vDate >= +todayZeroDate;
      const id = dayjs(vDate).format('YYYY-MM-DD');
      return {
        id,
        monthType: 'current',
        disabled: false,
        chose: choseDateList.includes(id),
        num: v,
        isRedDot,
      };
    });
    // 下月的部分数据
    const nextMonthNums = getDateListByMonth(cYear, cMonth + 1);
    const nextList = nextMonthNums
      .slice(0, 6 * 7 - preffixList.length - currentList.length)
      .map((v) => ({
        id: dayjs(new Date(cYear, cMonth, v)).format('YYYY-MM-DD'),
        monthType: 'next',
        disabled: true,
        num: v,
      }));

    // 给所有日期信息加上节气农历等信息
    let resDateList = [...preffixList, ...currentList, ...nextList].map((v) => {
      let date = v.id.split('-');
      let year = date[0];
      let mouth = date[1];
      let day = date[2];

      let dateParam = calendar.solar2lunar(year, mouth, day);
      return {
        ...v,
        ...dateParam,
      };
    });
    // 挂载时将当前年月日和本日信息传递到父组件中
    let currentDateInfo = resDateList.filter(
      (item) => item.id === choseDateList[0],
    );
    getYearAndMouth(currentDateInfo[0]);

    // 拼接
    setDateList([...resDateList]);
  }, [cYear, cMonth, choseDateList]);

  // 点击选中日期的事件
  const onClickDate = (item) => {
    if (item.disabled) {
      return;
    }
    const index = choseDateList.indexOf(item.id);
    if (index === -1) {
      choseDateList.push(item.id);
    } else {
      choseDateList.splice(index, 1);
    }
    let current = choseDateList[choseDateList.length - 1];
    setChoseDateList([current]);
  };

  return (
    <div className={styles.popupBody}>
      <div className={styles.main}>
        {/* 切换年月栏 */}
        {/* <div className={styles.topBar}>
          <div className={styles.topBarL}>
            <span onClick={() => onChangeYear(-1)}>--</span>
            <span onClick={() => onChangeMonth(-1)}>-</span>
          </div>
          <p className={styles.dateTxt}>
            {cYear}年{cMonth}月
          </p>
          <div className={styles.topBarR}>
            <span onClick={() => onChangeMonth(1)}>+</span>
            <span onClick={() => onChangeYear(1)}>++</span>
          </div>
        </div> */}

        {/* 星期栏 */}
        <div className={styles.weekBar}>
          {weekList.map((v) => (
            <div
              key={v}
              className={styles.weekCol}
              style={{ color: v === '日' || v === '六' ? 'red' : 'black' }}
            >
              {v}
            </div>
          ))}
        </div>

        {/* 日期栏 */}
        <div className={styles.dateWrap}>
          {dateList.map((v) => {
            return (
              <div
                key={v.id}
                className={`${styles.dateItem}
                ${v.disabled ? styles.grey : ''}
                ${v.chose ? styles.chose : ''}`}
                onClick={() => onClickDate(v)}
              >
                <div className={styles.numWrap}>
                  <span>{v.num}</span>
                  <span className={styles.noWrap}>
                    {v.isTerm ? v.Term : v.IDayCn}
                  </span>
                  {/* 当月剩余天的标记点 */}
                  {/* {v.isRedDot ? <i className={styles.dot} /> : null} */}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

export default Page;
